<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2019/1/21
 * Time: 10:35
 */

namespace api\storage\service;


use api\storage\common\Constant;
use api\storage\model\CarFileModel;
use api\storage\model\CarModel;
use api\storage\model\CarSeatModel;
use api\storage\model\OutflowModel;
use service\file\CommonFile;
use service\file\FileLock;
use service\logger\LoggerFactory;
use think\Cache;

class CarService extends BaseService
{
    private $currentACarId;
    private $currentACarUuid;
    private $currentAIndex = 0;
    private $currentBCarId;
    private $currentBCarUuid;
    private $currentBIndex = 0;
    private $currentCCarId;
    private $currentCCarUuid;
    private $currentCIndex = 0;
    private $carList;

    private $carModel;
    private $carSeatModel;

    private $logger;

    public function __construct()
    {
        $this->logger = LoggerFactory::getLogger('car');
        $this->carSeatModel = new CarSeatModel();
        $this->carModel = new CarModel();
    }

    /**
     * 获取出库流水的时间
     *
     * @param $bomId
     * @param $storageUuid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBomTime($bomId, $storageUuid)
    {
        $outflowModel = new OutflowModel();
        list($orderId, $fentryId) = BomService::judgeBomType($bomId);
        $outflow = $outflowModel->queryOutflow($orderId, $fentryId, $storageUuid);
        $times = [];
        foreach ($outflow as $item) {
            $time = $item->getData('time');
            $temp = substr($time, 0, 10);
            if (!in_array($temp, $times)) {
                array_push($times, $temp);
            }
        }
        sort($times);
        return $this->resultTemplate(1, ['times' => $times]);
    }

    /**
     * 获取小车规格 并且查看是否有数据
     *
     * @param $carId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCarNorm($carId)
    {
        $carModel = new CarModel();
        $car = $carModel->findByCarId($carId);
        if (empty($car) || empty($car->getData())) {
            return $this->resultTemplate(0, $this->returnCarNorm());
        } else {
            return $this->resultTemplate(1, $this->returnCarNorm($car->getData('a_count'), $car->getData('b_count'), $car->getData('status')));
        }
    }

    /**
     *  获取物料的数量
     *
     * @param $data
     * @param $storageUuid
     * @return array
     */
    public function getCarCount($data, $storageUuid)
    {
        $bomIds = [];
        foreach ($data as $item) {
            $bomIds[] = $item['bomId'];
            $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $item['bomId'] . Constant::RECORD_FILE_SUFFIX);
            if ($file->isExist()) {
                //查看这个出库单是不是正在装车的单子，如果是的话，直接进入装车操作
                $content = $this->jsonDecode($file->read());
                if (!empty($content) && isset($content['person']) && !empty($content['person'])) {
                    $content['person']++;
                    $file->write($content);
                    $this->logger->debug("bomId：{$item['bomId']}，进入多人装车");
                    return $this->resultTemplate(2);
                }
            }
        }
        list($finalData, $aCount, $bCount) = $this->getReelsDataAndCountByParam($data);
        if (empty($finalData)) {
            return $this->resultTemplate(-1);
        }
        //将文件写进预分配文件中
        $finalData['bomIds'] = $bomIds;
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_PREPARE_POSITION . $bomIds[0] . Constant::RECORD_FILE_SUFFIX);
        $file->write($finalData);
        return $this->resultTemplate(1, $this->returnCarNorm($aCount, $bCount));
    }

    /**
     * 分配站位
     * @param $carIds
     * @param $bomId
     * @param $isOverride
     * @param $status
     * @param $storageUuid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function distributeSeatCode($carIds, $bomId, $isOverride, $status, $storageUuid)
    {
        if ($isOverride) {
            $this->logger->debug("bomId：{$bomId},采用覆盖分配站位");
            $this->cleanCar($carIds);
            return $this->setSeatCodeByOverride($carIds, $bomId, $status, $storageUuid);
        } else {
            $this->logger->debug("bomId：{$bomId},采用追加分配站位");
            return $this->setSeatCodeByAppend($carIds, $bomId, $status, $storageUuid);
        }
    }

    /**
     * 获取站位信息
     *
     * @param $bomId
     * @param $reelId
     * @param $storageUuid
     * @param $nickname
     * @return array
     */
    public function getSeatCode($bomId, $reelId, $storageUuid, $nickname = '')
    {
        $this->logger->debug("用户：{$nickname}，bomId：{$bomId},reelId：{$reelId},开始查找小车位置");
        $lock = new FileLock($storageUuid);
        $lock->lock(FileLock::LOCK_TYPE_CAR_GET);
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($file->read());

        if (!isset($data['data'][$reelId])) {
            //该物料不是装车的物料
            $lock->unlock();
            $this->logger->debug("该reelId不是装车所需的物流");
            return $this->resultTemplate(-1, $this->returnSeatCode(null, null, true));
        }
        $reelInfo = $data['data'][$reelId];
        if (!empty($reelInfo['seatCode'])) {
            $carId = $reelInfo['carId'];
            $seatCode = $reelInfo['seatCode'];
            $this->logger->debug("从已经分配的reelInfo中找到：carId：{$carId},seatCode：{$seatCode}");
        } else {
            //找队首元素
            $materielId = $data['data'][$reelId]['materielId'];
            list($carId, $seatCode) = array_shift($data['seat'][$materielId]);
            $data['data'][$reelId]['carId'] = $carId;
            $data['data'][$reelId]['seatCode'] = $seatCode;
            $this->logger->debug("从data站位队列中找到：carId：{$carId},seatCode：{$seatCode}");
        }
        $file->write($data);
        $lock->unlock();
        $carModel = new CarModel();
        $carUuid = $carModel->findCarUuid($carId);
        $this->logger->debug("用户：{$nickname}，bomId：{$bomId},reelId：{$reelId},结束查找小车位置");
        SocketService::carSendToDb($seatCode, $carUuid, 1);
        return $this->resultTemplate(1, $this->returnSeatCode($carId, $seatCode, true));
    }

    /**
     * 将信息写入到占位里
     *
     * @param $bomId
     * @param $reelId
     * @param $seatCode
     * @param $storageUuid
     * @param $nickname
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function putSeat($bomId, $reelId, $seatCode, $storageUuid, $nickname = '')
    {
        $this->logger->debug("用户：{$nickname}，bomId：{$bomId}，reelId：{$reelId}，seatCode：{$seatCode}，开始放置物料");
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($file->read());
        $reelInfo = $data['data'][$reelId];
        if ($seatCode != $reelInfo['seatCode']) {
            $this->logger->debug("seatCode不匹配，期望的seatCode：{$reelInfo['seatCode']}，实际的seatCode：{$seatCode}");
            return $this->resultTemplate(-1);
        }
        $carId = $reelInfo['carId'];
        $carModel = new CarModel();
        $carSeatModel = new CarSeatModel();
        $carUuid = $carModel->findCarUuid($carId);
        $saveData['reel_id'] = $reelInfo['reelId'];
        $saveData['sub_materiel_id'] = $reelInfo['materielId'];
        $saveData['count'] = $reelInfo['count'];
        $res = $carSeatModel->updateSeat($carUuid, $seatCode, $saveData);
        $this->logger->debug("结束放置物料，写入的结果：{$res}");
        //将car数据表设置为使用,使用缓存的话，就不需要一直写数据库了
        $cacheCar = Cache::get(Constant::CACHE_PREFIX_CAR . $carId);
        if (empty($cacheCar)) {
            $carModel->updateStats($carId, 1);
            $car = $carModel->findByCarId($carId)->toArray();
            Cache::set(Constant::CACHE_PREFIX_CAR . $carId, $car, 3600);
        } else {
            if ($cacheCar['status'] == 0) {
                $carModel->updateStats($carId, 1);
                Cache::set(Constant::CACHE_PREFIX_CAR . $carId, null);
            }
        }

        if ($res !== false) {
            SocketService::carSendToDb($seatCode, $carUuid, 0);//站位确认后灭灯
            return $this->resultTemplate(1);
        } else {
            return $this->resultTemplate(0);
        }
    }

    /**
     * 主要用于装容器检查物料
     *
     * @param $bomId
     * @param $reelId
     * @param $storageUuid
     * @return array
     */
    public function checkReels($bomId, $reelId, $storageUuid)
    {
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($file->read());
        if (isset($data['data'][$reelId])) {
            return $this->resultTemplate(1);
        } else {
            return $this->resultTemplate(-1);
        }
    }

    /**
     * 将物料写进容器中
     *
     * @param $bomId
     * @param $reelIds
     * @param $containerCode
     * @param $storageUuid
     * @return array
     */
    public function putContainer($bomId, $reelIds, $containerCode, $storageUuid)
    {
        $lock = new FileLock($storageUuid);
        $lock->lock(FileLock::LOCK_TYPE_CAR_PUT);
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($file->read());

        foreach ($reelIds as $reelId) {
            if (isset($data['data'][$reelId])) {
                $data['data'][$reelId]['seatCode'] = $containerCode;
            }
        }
        $file->write($data);
        $lock->unlock();
        return $this->resultTemplate(1);
    }

    public function complete($bomId, $storageUuid, $nickname = '')
    {
        $lock = new FileLock($storageUuid);
        $lock->lock(FileLock::LOCK_TYPE_CAR_PUT);
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($file->read());

        if (isset($data['person']) && $data['person'] > 0) {
            $data['person']--;
            $file->write($data);
            $lock->unlock();
        }
        $this->logger->debug("用户：{$nickname}，bomId：{$bomId}结束装车");
        return $this->resultTemplate(1);
    }

    /**
     * 该方法给其他service调用，用于出库中
     *
     * @param $reels
     * @param $batchReels
     * @param $bomId
     * @param $storageUuid
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function prepareCarSeatData($reels, $bomId, $storageUuid)
    {
        $aCount = $bCount = 0;
        $finalData = [];
        //对sub_materiel_id进行排序处理
        $key = array_column($reels, 'materielId');
        array_multisort($key, SORT_ASC, $reels);
        foreach ($reels as $it) {
            $newReel['reelId'] = $it['reelId'];
            $newReel['materielId'] = $it['materielId'];
            $materiel = MaterielService::getMaterielCache($it['materielId']);
            $newReel['materielName'] = empty($materiel) ? '' : $materiel['sub_materiel_name'];
            $newReel['count'] = $it['count'];
            $newReel['type'] = empty($materiel) ? '' : $materiel['shelves_type'];
            $newReel['bomId'] = $bomId;
            $newReel['carId'] = null;
            $newReel['seatCode'] = null;
            $finalData['data'][$it['reelId']] = $newReel;
            switch ($newReel['type']) {
                case 'A':
                    $aCount++;
                    break;
                case 'B':
                    $bCount++;
                    break;
                default:
                    break;
            }
        }
        if (empty($finalData)) {
            return $this->resultTemplate(-1, $this->returnCarNorm());
        }
        //将文件写进预分配文件中
        $finalData['bomIds'] = [$bomId];
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_PREPARE_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $file->write($finalData);
        return $this->resultTemplate(1, $this->returnCarNorm($aCount, $bCount));
    }

    /**
     * 该方法给其他service调用，用于出库中
     *
     * @param $bomId
     * @param $reelId
     * @param $storageUuid
     * @return array
     */
    public function getCarPosition($bomId, $reelId, $storageUuid)
    {
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($file->read());
        //判断出库的物料是否在出库的信息里，因为容器的信息不再data里
        $isExist = array_key_exists($reelId, $data['data']);
        if ($isExist) {
            //如果存在，直接调用carService的获取站位
            return $this->getSeatCode($bomId, $reelId, $storageUuid);
        } else {
            //如果不存在，说明把该物料放置容器上即可
            $carId = $data['carIds'][0];
            return $this->resultTemplate(1, $this->returnSeatCode($carId, null, true));
        }
    }

    /**
     * 设置小车的占位（覆盖式）
     *
     * @param $carIds
     * @param $bomId
     * @param $status
     * @param $storageUuid
     * @return array
     */
    private function setSeatCodeByOverride($carIds, $bomId, $status, $storageUuid)
    {
        $prepareFile = new CommonFile($storageUuid, Constant::RECORD_CAR_PREPARE_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($prepareFile->read());
        $this->currentACarId = $this->currentBCarId = $this->currentCCarId = $carIds[0];
        $this->carList = $carIds;
        $seat = [];
        $this->carModel = new CarModel();
        $this->carSeatModel = new CarSeatModel();
        foreach ($data['data'] as &$item) {
            list($carId, $seatCode) = $this->getNotUsedSeatCode($item['type']);
            $item['carId'] = null;
            $item['seatCode'] = null;
            if (empty($seat) || empty($seat[$item['materielId']])) {
                $seat[$item['materielId']][] = [$carId, $seatCode];
            } else {
                array_push($seat[$item['materielId']], [$carId, $seatCode]);
            }
        }
        $data['seat'] = $seat;
        $data['carIds'] = $carIds;
        $data['person'] = 1;
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $file->write($data);
        //记录文件内容
        $this->storeFilePath($file->getPath(), $data['bomIds'], $storageUuid);
        //可以考虑一下要不要删除
//        $prepareFile->delete()
        return $this->resultTemplate(1);
    }

    /***
     * 设置小车的占位（追加式）
     * @param $carIds
     * @param $bomId
     * @param $status
     * @param $storageUuid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function setSeatCodeByAppend($carIds, $bomId, $status, $storageUuid)
    {

        $prepareFile = new CommonFile($storageUuid, Constant::RECORD_CAR_PREPARE_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $prepareData = $this->jsonDecode($prepareFile->read());
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        $data = $this->jsonDecode($file->read());
        //排除差异，得出来的就是新的数据
        $newData = array_diff_key($prepareData['data'], $data);
        $this->currentACarId = $this->currentBCarId = $this->currentCCarId = $carIds[0];
        $this->carList = $carIds;
        $seat = [];
        $this->carModel = new CarModel();
        $this->carSeatModel = new CarSeatModel();
        foreach ($data['data'] as &$item) {
            list($carId, $seatCode) = $this->getNotUsedSeatCode($item['type']);
            $item['carId'] = null;
            $item['seatCode'] = null;
            if (empty($seat)) {
                $seat[$item['materielId']][] = [$carId, $seatCode];
            } else {
                array_push($seat[$item['materielId']], [$carId, $seatCode]);
            }
        }
        //合并数据
        $data['data'] = array_merge($data['data'], $newData);
        $data['seat'] = array_merge($data['seat'], $seat);
        $data['carIds'] = array_values(array_unique(array_merge($data['carIds'], $carIds)));
        $data['bomIds'] = array_values(array_unique(array_merge($prepareData['bomIds'], $data['bomIds'])));
        $data['person'] = 1;
        $file->write($data);
        //记录文件内容
        $this->storeFilePath($file->getPath(), $prepareData['bomIds'], $storageUuid);
        return $this->resultTemplate(1);
    }


    /**
     * 清除小车的使用
     *
     * @param $carIds
     */
    private function cleanCar($carIds)
    {
        $carModel = new CarModel();
        $carSeatModel = new CarSeatModel();
        foreach ($carIds as $id) {
            $carModel->updateStats($id);
            $carUuid = $carModel->findCarUuid($id);
            $carSeatModel->cleanCarSeat($carUuid);
            Cache::set(Constant::CACHE_PREFIX_CAR . $id, null);
        }
    }

    /***取消装车操作
     * @param $bomId
     * @param $storageUuid
     * @param $reelId
     * @return array
     */
    public function cancelPutSeat($bomId, $storageUuid, $reelId)
    {
        $file = new CommonFile($storageUuid, Constant::RECORD_CAR_POSITION . $bomId . Constant::RECORD_FILE_SUFFIX);
        //读取文件data/carPosition/storageUuid/bomId.json
        $fileData = $this->jsonDecode($file->read());
        $carId = $fileData['data'][$reelId]['carId'];
        $seatCode = $fileData['data'][$reelId]['seatCode'];
        $materielId = $fileData['data'][$reelId]['materielId'];
        array_push($fileData['seat'][$materielId], array($carId, $seatCode));//将当前物料分配到的carId和seatCode追加回materielId下
        $fileData['data'][$reelId]['carId'] = NULL;
        $fileData['data'][$reelId]['seatCode'] = NULL;
        $file->write($fileData);
        SocketService::carSendToDb($seatCode, $carId, 0);
        return $this->resultTemplate(1);
        /***
         * 这段应该结合carPosition文件来看
         *当扫描要装车的物料以后，他会从
         * "seat": {}内
         * 与扫描物料相对应的materielId下获取一个[小车地址,站位地址]
         * 分别放入到对应reel{}下的seatCode和carId中，
         *取消的原理就是将reel{}下的seatCode和carId写回对应的materielId，然后将两者改回NULL
         */
    }


    /**
     * 存储小车文件信息
     *
     * @param $path
     * @param array $bomIds
     * @param $storageUuid
     * @return bool|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function storeFilePath($path, $bomIds = [], $storageUuid)
    {
        if (empty($bomIds)) {
            return;
        }
        if (!is_array($bomIds)) {
            $bomIds = [$bomIds];
        }
        $carFileModel = new CarFileModel();
        foreach ($bomIds as $bomId) {
            $bom = BomService::getBomInfo($bomId);
            $bomUuid = empty($bom) || empty($bom->getData()) ? '' : $bom->getData('uuid');
            $carFileModel->add([
                'file_path' => $path,
                'bom_id' => $bomId,
                'bom_uuid' => $bomUuid,
                'storage_uuid' => $storageUuid,
                'time' => get_current_time()
            ]);
        }

    }

    /**
     * 根据一些参数来获取物料的信息
     *
     * @param array $param
     * @return array
     */
    private function getReelsDataAndCountByParam($param = [])
    {
        $data = [];
        $outflowModel = new OutflowModel();
        foreach ($param as $item) {
            list($orderId, $fentryId) = BomService::judgeBomType($item['bomId']);
            $where['order_id'] = $orderId;
            if (!empty($fentryId)) {
                $where['fentryid'] = $fentryId;
            }
            if (isset($item['time']) && !empty($item['time'])) {
                $temp = [];
                foreach ($item['time'] as $it) {
                    $temp[] = $it . '%';
                }
                $where['time'] = ['like', $temp, 'OR'];
            }
            $res = $outflowModel->queryOutflowByWhere($where)->toArray();
            $data = array_merge($res, $data);
        }
        $aCount = $bCount = 0;
        $finalData = [];
        //对sub_materiel_id进行排序处理
        $key = array_column($data, 'sub_materiel_id');
        array_multisort($key, SORT_ASC, $data);
        foreach ($data as $it) {
            $tempId = !empty($it['fentryid']) ? '+' . $it['fentryid'] : '';
            $newReel['reelId'] = $it['reel_id'];
            $newReel['materielId'] = $it['sub_materiel_id'];
            $newReel['materielName'] = $it['sub_materiel_name'];
            $newReel['count'] = $it['count'];
            $newReel['type'] = $it['type'];
            $newReel['bomId'] = $it['order_id'] . $tempId;
            $newReel['carId'] = null;
            $newReel['seatCode'] = null;

            unset($it['fentryid']);
            unset($it['order_id']);

            $finalData['data'][$it['reel_id']] = $newReel;
            switch ($it['type']) {
                case 'A':
                    $aCount++;
                    break;
                case 'B':
                    $bCount++;
                    break;
                default:
                    break;
            }
        }
        return [$finalData, $aCount, $bCount];
    }

    /**
     * 获取没有使用的占位
     *
     * @param string $type
     * @return array
     */
    private function getNotUsedSeatCode($type = 'A')
    {
        switch ($type) {
            case 'A':
                if (empty($this->currentACarUuid)) {
                    $this->currentACarUuid = $this->carModel->findCarUuid($this->currentACarId);
                }
                $seatCode = $this->carSeatModel->findNotUsedSeatCode($this->currentACarUuid, $type);
                if (!empty($seatCode)) {
                    //将这个位置占用
                    $this->carSeatModel->updateIsUsed($this->currentACarUuid, $seatCode);
                    return $this->returnSeatCode($this->currentACarId, $seatCode);
                } else {
                    //没有找到，这个时候可能是要换车了
                    $this->currentAIndex++;
                    if ($this->currentAIndex >= count($this->carList)) {
                        //小车列表已经到头了,换一个C的占位给他
                        return $this->getNotUsedSeatCode('C');
                    } else {
                        //如果还有小车的话
                        $this->currentACarId = $this->carList[$this->currentAIndex];
                        $this->currentACarUuid = $this->carModel->findCarUuid($this->currentACarId);
                        return $this->getNotUsedSeatCode($type);
                    }
                }
                break;
            case 'B':
                if (empty($this->currentBCarUuid)) {
                    $this->currentBCarUuid = $this->carModel->findCarUuid($this->currentBCarId);
                }
                $seatCode = $this->carSeatModel->findNotUsedSeatCode($this->currentBCarUuid, $type);
                if (!empty($seatCode)) {
                    //将这个位置占用
                    $this->carSeatModel->updateIsUsed($this->currentBCarUuid, $seatCode);
                    return $this->returnSeatCode($this->currentBCarId, $seatCode);
                } else {
                    //没有找到，这个时候可能是要换车了
                    $this->currentBIndex++;
                    if ($this->currentBIndex >= count($this->carList)) {
                        //小车列表已经到头了,换一个C的占位给他
                        return $this->getNotUsedSeatCode('C');
                    } else {
                        //如果还有小车的话
                        $this->currentBCarId = $this->carList[$this->currentBIndex];
                        $this->currentBCarUuid = $this->carModel->findCarUuid($this->currentBCarId);
                        return $this->getNotUsedSeatCode($type);
                    }
                }
                break;
            case 'C':
                if (empty($this->currentCCarUuid)) {
                    $this->currentCCarUuid = $this->carModel->findCarUuid($this->currentCCarId);
                }
                $seatCode = $this->carSeatModel->findNotUsedSeatCode($this->currentCCarUuid, $type);
                if (!empty($seatCode)) {
                    //不将位置占用
                    return $this->returnSeatCode($this->currentCCarId, $seatCode);
                } else {
                    //没有找到，这个时候可能是要换车了
                    $this->currentCIndex++;
                    if ($this->currentCIndex >= count($this->carList)) {
                        //如果C占位都没有位置的话，直接返回null
                        return $this->returnSeatCode();
                    } else {
                        //如果还有小车的话
                        $this->currentCCarId = $this->carList[$this->currentCIndex];
                        $this->currentCCarUuid = $this->carModel->findCarUuid($this->currentCIndex);
                        return $this->getNotUsedSeatCode($type);
                    }
                }
                break;
            default:
                return $this->returnSeatCode();
        }
    }

    private function returnSeatCode($carId = null, $seatCode = null, $hasWrap = false)
    {
        if ($hasWrap) {
            return [
                'carId' => $carId,
                'seatCode' => $seatCode
            ];
        }
        return [$carId, $seatCode];
    }

    private function returnCarNorm($ac = 0, $bc = 0, $status = 0, $isMoveStatus = false)
    {
        if ($isMoveStatus) {
            return [
                'aCount' => $ac,
                'bCount' => $bc,
            ];
        } else {
            return [
                'aCount' => $ac,
                'bCount' => $bc,
                'hasData' => $status
            ];
        }

    }


}